package framework

import (
	"fmt"
	"log"
	"net/http"
	"runtime/debug"
)

//Router 定义路由
var Router *RouterHandler = new(RouterHandler)

//RouterHandler 定义路由handler
type RouterHandler struct {
}

var mux = make(map[string]func(http.ResponseWriter, *http.Request))

func (p *RouterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.URL.Path)
	log.Println(mux)
	if fun, ok := mux[r.URL.Path]; ok {
		fun(w, r)
		return
	}

	http.Error(w, "error URL:"+r.URL.String(), http.StatusBadRequest)
}

//Router 添加路由
func (p *RouterHandler) Router(relativePath string, handler func(http.ResponseWriter, *http.Request)) {
	mux[relativePath] = safeHandler(handler)
}

func safeHandler(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		r.ParseMultipartForm(32 << 20)
		defer func() {
			if e, ok := recover().(error); ok {
				http.Error(w, e.Error(), http.StatusInternalServerError)
				// 或者输出自定义的50x错误页面
				// w.WriteHeader(http.StatusInternalServerError)
				// renderHtml(w, "error", e)
				// logging
				log.Println("WARN: panic in %v. - %v", fn, e)
				log.Println(string(debug.Stack()))
			}
		}()
		fn(w, r)
	}
}
